package com.httpgetandpost;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final int GET_RESULT = 1;
    private final String TAG = "MainActivity";
    private EditText editPhone;
    private TextView txtResult;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editPhone = findViewById(R.id.edt_phone);
        txtResult = findViewById(R.id.txt_result);

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == GET_RESULT){
                    String html = (String) msg.obj;
                    txtResult.setText(html);
                    return true;
                }
                return false;
            }
        });
        findViewById(R.id.HttpGet).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = editPhone.getText().toString();
                //网络访问要放在新的线程
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        useHttpGet(phone);
                    }
                }).start();
            }
        });
        findViewById(R.id.HttpPost).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = editPhone.getText().toString();
                //网络访问要放在新的线程
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        useHttpPost(phone);
                    }
                }).start();
            }
        });
    }

    private void useHttpPost(String phone) {
        //获取httpClient
        String url = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        //mobileCode和userID数据存入nameValuePairList
        List<NameValuePair> nameValuePairList = new ArrayList<>();
        nameValuePairList.add(new BasicNameValuePair("mobileCode", phone));
        nameValuePairList.add(new BasicNameValuePair("userID", ""));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList));
            //获取http响应
            HttpResponse httpResponse = httpClient.execute(httpPost);
            //获取响应状态码
            int code = httpResponse.getStatusLine().getStatusCode();
            Log.e(TAG, "httpResponseGetStatusCode = " + code);

            //获取html内容
            String htmlContent = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            Log.e(TAG, htmlContent);

            //实例化消息对象
            Message message = Message.obtain();
            message.what = 1;//消息标识
            message.obj = htmlContent;//消息内容
            //通过handler发送消息
            handler.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void useHttpGet(String phone) {
        //获取httpClient
        String url = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=";
        url = url.concat(phone).concat("&userID=");
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);

        try {
            //获取http响应
            HttpResponse httpResponse = httpClient.execute(httpGet);
            //获取响应状态码
            int code = httpResponse.getStatusLine().getStatusCode();
            Log.e(TAG, "httpResponseGetStatusCode = " + code);

            //获取html内容
//            String htmlContent = GetHtmlContent(httpResponse);
            String htmlContent = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            Log.e(TAG, htmlContent);

            //实例化消息对象
            Message message = Message.obtain();
            message.what = 1;//消息标识
            message.obj = htmlContent;//消息内容
            //通过handler发送消息
            handler.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String GetHtmlContent(HttpResponse httpResponse) throws IOException {
        //获取网页实体内容
        InputStream inputStream = httpResponse.getEntity().getContent();
        //用BufferedReader读取内容
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer stringBuffer = new StringBuffer();
        //读取bufferedReader数据存入stringBuffer
        String line = bufferedReader.readLine();
        while (line != null) {
            stringBuffer.append(line);
            line = bufferedReader.readLine();
        }

        inputStream.close();
        bufferedReader.close();

        return stringBuffer.toString();
    }
}
